<?php

namespace app\admin\controller;

use app\admin\library\Excel;
use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 车辆信息
 *
 */
class XCarinfo extends Backend
{
    /**
     * XCarinfo模型对象
     * @var \app\admin\model\XCarinfo
     */
    protected $model = null;
    
    protected $quickSearchField = ['ID'];

    protected $defaultSortField = 'ID,desc';
    protected $noNeedLogin      = ['*'];
    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XCarinfo;
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $wheres='';
        $crop=$this->request->get('CORP');
        if($crop){
            $wheres=['CORP'=>$crop];
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($wheres)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);
    }

    public function importData()
    {
        // 接收文件上传信息
        $files = $this->request->file("file");
        $CORP=$this->request->post('corp');
        // 调用类库，读取excel中的内容
        $data = Excel::importExcel($files);
        $type=$data[0][0];
        $k=['0'=>'','1'=>'','2'=>'',];
        $data=array_diff_key($data,$k);
        $add=[];
        $adminInfo          = $this->auth->getInfo();
        foreach ($data as $k=>$datum) {
            $add[$k]['BRAND']=$datum[1];
            $add[$k]['TRUCKNO']=$datum[2];
            $add[$k]['CORP']=$CORP;

            $add[$k]['ZBWEIGHT']=$datum[4];
            $add[$k]['AXLE']=$datum[5];
            $add[$k]['FIRSTDATE']=date('Y-m-d', ($datum[6] - 25569) * 24 * 3600);;
            $add[$k]['JYDATE']=date('Y-m-d', ($datum[7] - 25569) * 24 * 3600);;
            if($type=='半挂车'){
                $add[$k]['HDWEIGHT']=$datum[3];
                $add[$k]['SIZE']=$datum[8];
                $add[$k]['ABS']=$datum[9];
                $add[$k]['ROADNUMBER']=$datum[10];
                $add[$k]['SCOPE']=$datum[11];
                $add[$k]['ROADDATE']=date('Y-m-d', ($datum[12] - 25569) * 24 * 3600);;
                $add[$k]['POLICYTYPE']=$datum[13];
                $add[$k]['POLICYNO']=$datum[14];
                $add[$k]['POLICYDATE']=date('Y-m-d', ($datum[15] - 25569) * 24 * 3600);;
                $add[$k]['DEMO']=$datum[16];
            }else{
                $add[$k]['QYWEIGHT']=$datum[3];
                $add[$k]['GPS']=$datum[8];
                $add[$k]['GPSSHIP']=$datum[9];
                $add[$k]['VDSIVMS']=$datum[10];
                $add[$k]['ABS']=$datum[11];
                $add[$k]['ROADNUMBER']=$datum[12];
                $add[$k]['SCOPE']=$datum[13];
                $add[$k]['ROADDATE']=date('Y-m-d', ($datum[14] - 25569) * 24 * 3600);;
                $add[$k]['POLICYTYPE']=$datum[15];
                $add[$k]['POLICYNO']=$datum[16];
                $add[$k]['POLICYDATE']=date('Y-m-d', ($datum[17] - 25569) * 24 * 3600);;
                $add[$k]['DEMO']=$datum[18];
            }
            $add[$k]['STATUS']='1';
            $add[$k]['OP']=$adminInfo['nickname'];
            $add[$k]['OPTIME']=date('Y-m-d H:i:s',time());
        }
        $result = false;
       Db::startTrans();
        try {

            $result=$this->model->insertAll($add);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            $this->success(__('Added successfully'));
        } else {
            $this->error(__('No rows were added'));
        }
    }
}